package com.woniu.bh.backstage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.bh.backstage.dao.ManagerMapper;
import com.woniu.bh.backstage.dto.ManagerDto;
import com.woniu.bh.backstage.dto.PageResult;
import com.woniu.bh.backstage.param.AddManagerParam;
import com.woniu.bh.backstage.param.ManagerParam;
import com.woniu.bh.backstage.param.ModifyPwdParam;
import com.woniu.bh.backstage.service.IManagerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.bh.backstage.util.Constants;
import com.woniu.bh.backstage.util.EncryUtils;
import com.woniu.bh.common.core.domain.backstage.Manager;
import com.woniu.bh.common.core.dto.ResultDto;
import com.woniu.bh.common.core.exception.ProjectExceptionResult;
import com.woniu.bh.common.core.util.MessageHandler;
import com.woniu.bh.common.core.util.RandomId;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.jar.Manifest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxb
 * @since 2020-10-13
 */
@Service
@Slf4j
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements IManagerService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ManagerMapper managerMapper;

    @Override
    public ResultDto login(ManagerParam managerParam) {
        //获取数据库中记录的加密密码
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_name",managerParam.getName());
        Manager manager = managerMapper.selectOne(wrapper);
        if(manager==null){
            return ResultDto.fail(ProjectExceptionResult.USER_NOT_EXSIT.getCode(),ProjectExceptionResult.USER_NOT_EXSIT.getMessage());//用户不存在
        }
        String encryPassword = manager.getManagerPassword();
        String inputEncryPassword = null;
        //对比输入的密码加密结果
        try {
            EncryUtils des = new EncryUtils(Constants.SECRETKEY, "utf-8");
            inputEncryPassword = des.encode(managerParam.getPass());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(inputEncryPassword+"-----"+encryPassword);
        if(isForbidden(managerParam.getName())){
            return ResultDto.builder().code(ProjectExceptionResult.USER_FORBIDDEN.getCode()).message(ProjectExceptionResult.USER_FORBIDDEN.getMessage()).build();//用户已冻结
        }
        if(!encryPassword.equals(inputEncryPassword)){
            return ResultDto.builder().code(ProjectExceptionResult.USER_OR_PWD_ERROR.getCode()).message(ProjectExceptionResult.USER_OR_PWD_ERROR.getMessage()).build();//密码错误
        }else {
            //更新登陆时间
            QueryWrapper<Manager> wrapper1  = new QueryWrapper<>();
            wrapper1.eq("manager_name",managerParam.getName());
            Manager manager1 =new Manager();
            manager1.setManagerLastLoginTime(System.currentTimeMillis());
            managerMapper.update(manager1,wrapper);
            return ResultDto.builder().code(ProjectExceptionResult.SUCCESS.getCode()).message(ProjectExceptionResult.SUCCESS.getMessage()).success(true).object(manager).build();//密码正确
        }
    }

    @Override
    public boolean isForbidden(String name) {
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_name",name);
        Manager manager = managerMapper.selectOne(wrapper);
        Integer status = manager.getManagerStatus();
        return status.equals(Constants.USER_FORBIDDEN);
    }

    @Override
    public String getVerifyCode(String phone) {
        MessageHandler messageHandler = new MessageHandler();
        //生成动态验证码并存入redis中
        String code = RandomId.getCode(4);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        //发送短信    "SMS_204297678"是已经自定义的项目短信模板，写死
        boolean isSend = messageHandler.send(phone,"SMS_204297678",param);
        if (isSend){
            //存入redis（可以用redis暂存，校验
            redisTemplate.opsForValue().set(phone,code,60*60*24, TimeUnit.SECONDS);
            return code;
        }else {
            return null;
        }
    }

    @Override
    public ManagerDto selectByPhone(String phone) {
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_phone",phone);
        Manager manager = managerMapper.selectOne(wrapper);
        System.out.println(manager);
        if(manager!=null){
            ManagerDto managerDto = new ManagerDto();
            BeanUtils.copyProperties(manager,managerDto);
            return managerDto;
        }
        return null;
    }

    @Override
    public void modifyPwd(ModifyPwdParam modifyPwdParam) {
        String phone = modifyPwdParam.getPhone();
        String newpwd = modifyPwdParam.getNewPassword();
        //加密
        EncryUtils des = null;
        String newEncryptPwd =null;
        try {
            des = new EncryUtils(Constants.SECRETKEY, "utf-8");
            newEncryptPwd = des.encode(newpwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Manager manager = new Manager();
        manager.setManagerPhone(phone);
        manager.setManagerPassword(newEncryptPwd);
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_phone",phone);
        managerMapper.update(manager,wrapper);
    }

    @Override
    public ManagerDto selectManagerById(Integer id) {
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_id",id);
        Manager manager = managerMapper.selectById(id);
        System.out.println(manager.toString());
        ManagerDto managerDto = new ManagerDto();
        BeanUtils.copyProperties(manager,managerDto);
        return managerDto;
    }

    @Override
    public IPage<ManagerDto> selectPage(Integer pageIndex, Integer pageSize, Integer managerStatus, long dateAfter, long dateBefore) {
        Page<ManagerDto> page = new Page<>(pageIndex,pageSize);
        log.info("进入serviceimpl");
        IPage<ManagerDto> managerDtoIPage = managerMapper.queryPage2(page, managerStatus, dateAfter, dateBefore);
        return managerDtoIPage;
    }

    @Override
    public ManagerDto freezeManager(Integer id) {
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_id",id);
        Manager manager = managerMapper.selectOne(wrapper);
        if(manager!=null){
            manager.setManagerStatus(2);
            managerMapper.updateById(manager);
            ManagerDto managerDto = new ManagerDto();
            BeanUtils.copyProperties(manager,managerDto);
            return managerDto;
        }else {
            return null;
        }
    }

    @Override
    public ManagerDto unFreezeManager(Integer id) {
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_id",id);
        Manager manager = managerMapper.selectOne(wrapper);
        if(manager!=null){
            manager.setManagerStatus(1);
            managerMapper.updateById(manager);
            ManagerDto managerDto = new ManagerDto();
            BeanUtils.copyProperties(manager,managerDto);
            return managerDto;
        }else {
            return null;
        }
    }

    @Override
    public ResultDto addManager(AddManagerParam addManagerParam) {
        //检查新增用户名和电话是否重复
        String name = addManagerParam.getManagerName();
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("manager_name",name);
        Manager manager = managerMapper.selectOne(wrapper);
        if(manager!=null) return ResultDto.fail(ProjectExceptionResult.USER_NAME_IS_EXSIT);

        String phone = addManagerParam.getManagerPhone();
        QueryWrapper<Manager> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("manager_phone",phone);
        manager = managerMapper.selectOne(wrapper1);
        if(manager!=null) return ResultDto.fail(ProjectExceptionResult.USER_PHONE_IS_EXSIT);

        //加密用户密码
        String pass = addManagerParam.getManagerPassword();
        EncryUtils des = null;
        try {
            des = new EncryUtils(Constants.SECRETKEY, "utf-8");
            pass = des.encode(pass);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置管理员其他默认值属性
        manager= new Manager();
        BeanUtils.copyProperties(addManagerParam,manager);
        manager.setManagerStatus(1);
        manager.setManagerType(1);

        managerMapper.insert(manager);
        return ResultDto.success(ProjectExceptionResult.SUCCESS);
    }
}
